<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use GatewayWorker\BusinessWorker;
use GatewayWorker\Gateway;
use GatewayWorker\Register;
use function Matrix\identity;
use Workerman\Worker;
use Illuminate\Support\Facades\DB;
use App;
use App\Models\CarModels\Pgsql;

class WorkermanCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'workerman {action} {--d}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Start a Workerman server.';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    protected $dbs;
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        global $argv;
        $arg = $this->argument('action');
        $argv[1] = $argv[2];
        $argv[2] = isset($argv[3]) ? "-{$argv[3]}" : '';

        $this->start();
    }

    private function start()
    {
        $this->startGateWay();
        $this->startBusinessWorker();
        $this->startRegister();
//        $this->tcpStart();
        Worker::runAll();
    }

    private function tcpStart()
    {
        global $db;
        $db = new Pgsql(env('DB_HOST'), env('DB_PORT'), env('DB_USERNAME'), env('DB_PASSWORD'), env('DB_DATABASE'));
        $tcp_worker = new Worker("tcp://0.0.0.0:19527");
        $tcp_worker->count = 20;
        $tcp_worker->onWorkerStart = function () {
            $this->dbs = [];
        };
        $tcp_worker->onConnect = function ($connection){
            //在链接建立的时候建立mysql链接 链接断开的时候断开mysql链接

            $db = new Pgsql(env('DB_HOST'), env('DB_PORT'), env('DB_USERNAME'), env('DB_PASSWORD'), env('DB_DATABASE'));
            $cid = spl_object_id($connection);
            $this->dbs[$cid] = $db;
            //$connection->onMessage = function ($connection,$data){
//                echo $data;
//                global $db;
                //$db = new Pgsql(env('DB_HOST'), env('DB_PORT'), env('DB_USERNAME'), env('DB_PASSWORD'), env('DB_DATABASE'));
                //$cid = spl_object_id($connection);
                //$db = $this->dbs[$cid];
                //$this->dbs[$cid]
//                //把数据插入到timescaledb
//                $data = json_decode($data);
//                $time = date('Y-m-d H:i:s');
//                try {
//                    $db->query("INSERT INTO paths (time,nodeid,lon,lat)
//VALUES(" . "'{$time}'" . ",{$data->nodeid},{$data->lon},{$data->lat}) RETURNING *");
//                }catch (\Exception $e){
//
//                    var_dump($data);
//                    echo $e->getMessage();
//                }
            };
        //};
        $tcp_worker->onMessage = function ($connection, $data) {
            global $db;
            //$db = new Pgsql(env('DB_HOST'), env('DB_PORT'), env('DB_USERNAME'), env('DB_PASSWORD'), env('DB_DATABASE'));
            $cid = spl_object_id($connection);
            $db = $this->dbs[$cid];
           // 把数据插入到timescaledb
            $data = json_decode($data);
            $time = date('Y-m-d H:i:s');
            try {
                $db->query("INSERT INTO paths (time,nodeid,lon,lat)
VALUES(" . "'{$time}'" . ",{$data->nodeid},{$data->lon},{$data->lat}) RETURNING *");
            }catch (\Exception $e){

                var_dump($data);
                echo $e->getMessage();
            }
        };
    }

    //启动Register服务，用于gateway-worker内部通讯
    private function startRegister()
    {
        new Register('text://0.0.0.0:51235');
    }

    //启动gateway进程，用于暴露给客户端让其连接
    private function startGateWay()
    {
//        $gateway = new Gateway("websocket://0.0.0.0:23460");   //0.0.0.0 监听本机所有网卡（内网、外网、都可以访问）
//        $gateway->name = 'Gateway';                         //Gateway进程的名称
//        $gateway->count = 1;                                 //进程的数量=cup核心数。优化好linux内核，安装event扩展 每个进程可以维持上万的并发连接，否则只能1024个。
//        $gateway->lanIp = '0.0.0.0';                       //内网ip,多服务器分布式部署的时候需要填写真实的内网ip
//        $gateway->startPort = 2300;                              //监听本机端口的起始端口
//        $gateway->pingInterval = 30;                                //心跳检测时间间隔 单位：秒。如果设置为0代表不做任何心跳检测。
//        $gateway->pingNotResponseLimit = 0;                                 //客户端连续n次$pingInterval时间内不发送任何数据则断开链接，并触发onClose。0表示不发送（由服务端发送）
//        $gateway->pingData = '{"mode":"heart"}';                //服务端定时给客户端发送的心跳数据
//        $gateway->registerAddress = '0.0.0.0:12360';                 //注册服务地址

        $gateway = new Gateway("websocket://0.0.0.0:52347");
        $gateway->name                 = 'Gateway';
        $gateway->count                = 4;
        $gateway->lanIp                = '0.0.0.0';
        $gateway->startPort            = 2300;
        $gateway->pingInterval         = 3000;
        $gateway->pingNotResponseLimit = 0;
        $gateway->pingData             = '{"type":"@heart@"}';
        $gateway->registerAddress      = '0.0.0.0:51235';
    }


    //启动BusinessWorker进程，用于运行业务逻辑
    private function startBusinessWorker()
    {
//        $worker = new BusinessWorker();
//        $worker->name = 'BusinessWorker';                        //BusinessWorker进程的名称
//        $worker->count = 2;                                       //BusinessWorker进程的数量 = cup核心数的1-3倍
//        $worker->registerAddress = '0.0.0.0:12360';                       //注册服务地址
//        $worker->eventHandler = \App\Workerman\Events::class;        //设置使用哪个类来处理业务

        $worker                  = new BusinessWorker();
        $worker->name            = 'BusinessWorker';
        $worker->count           = 1;
        $worker->registerAddress = '0.0.0.0:51235';
        $worker->eventHandler    = App\Workerman\Events::class;
    }

}
